import Vue from 'vue'
import Router from 'vue-router'
import routers from '../components/sysRouterList';
import store from '.././vuex/store'
import {getToken} from "../utils/auth";

Vue.use(Router)

const router = new Router({
  routes: routers
})

// 在免登录白名单，直接进入
const whiteList = ['/login'];

router.beforeEach((to,from,next) => {
  if(getToken()){
    if (to.path === '/login') {
      next({ path: '/' });
    }else if(to.path === '/' || to.path === '/main'){
      next({ path: '/main' })
    }
    else{
        //当刷新页面时，跳转到默认页面。
        if((from.fullPath == '/' || from.fullPath == '/login') && to.path != store.state.currentView){
          next({ path: store.state.currentView });
        }else{
          if(to.matched == null || to.matched.length < 1){
          //组件未找到(需要判断一级菜单，然后修改路径。)
            next({ path: '/main/notFound' })
          }else{
            next();
            store.commit("routerChangePage",to.path);
          }
        }
    }
  }else{
    if (whiteList.indexOf(to.path)> -1) {
      next()
    } else {
      next('/login'); // 否则全部重定向到登录页
    }
  }
});


export default router;
